package com.efounder.frame.listener;

import android.app.Activity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;

import com.efounder.mobilemanager.R;

/**
 * Created by XinQing on 2016/12/30.
 */

public class EFOnTouchBackListener implements View.OnTouchListener{
    //X轴触发范围（单位dp）
    protected static final int Y_DISTANCE = 70;
    //Y轴触发范围（单位dp）
    protected static final int X_DISTANCE = 70;
    //手指向右滑动时的最小速度
    protected static final int X_SPEED_MIN = 200;
    protected Activity activity;
    protected float downX;
    protected float downY;
    protected int xTriggerRange;//X轴触发范围
    protected int yTriggerRange;//Y轴触发范围
    //用于计算手指滑动的速度。
    protected VelocityTracker mVelocityTracker;

    public EFOnTouchBackListener(Activity activity) {
        this.activity = activity;
        xTriggerRange = (int) (X_DISTANCE * activity.getResources().getDisplayMetrics().density);
        yTriggerRange = (int) (Y_DISTANCE * activity.getResources().getDisplayMetrics().density);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        Log.i("EFActivity","EFActivity-----onTouch");
        createVelocityTracker(event);
        if (v.getId() == R.id.rootLayout){//中间内容区域，右滑返回
            switch (event.getAction()){
                case MotionEvent.ACTION_DOWN:
                    downX = event.getX();
                    downY = event.getY();
                    break;
                case MotionEvent.ACTION_MOVE:
                    break;
                case MotionEvent.ACTION_UP:
                    //获取顺时速度
                    int xSpeed = getScrollVelocity();
                    if (Math.abs(event.getY() - downY) < yTriggerRange
                            && event.getX() - downX > xTriggerRange
                            && xSpeed > X_SPEED_MIN){
                        activity.finish();
                    }
                    recycleVelocityTracker();
                    break;
            }
        }
        return true;
    }


    /**
     * 创建VelocityTracker对象，并将触摸content界面的滑动事件加入到VelocityTracker当中。
     *
     * @param event
     */
    protected void createVelocityTracker(MotionEvent event) {
        if (mVelocityTracker == null) {
            mVelocityTracker = VelocityTracker.obtain();
        }
        mVelocityTracker.addMovement(event);
    }

    /**
     * 回收VelocityTracker对象。
     */
    protected void recycleVelocityTracker() {
        mVelocityTracker.recycle();
        mVelocityTracker = null;
    }

    /**
     * 获取手指在content界面滑动的速度。
     *
     * @return 滑动速度，以每秒钟移动了多少像素值为单位。
     */
    protected int getScrollVelocity() {
        mVelocityTracker.computeCurrentVelocity(1000);
        int velocity = (int) mVelocityTracker.getXVelocity();
        return Math.abs(velocity);
    }
}
